package controllers

import (
	"github.com/astaxie/beego/orm"
	"map/libs"
	"map/models"
	"path"
	"strconv"
	"time"
)

type AdminController struct {
	BaseController
}

func (this *AdminController) Present() {
	admin := make(map[string]interface{})
	admin["id"] = this.admin.Id
	admin["username"] = this.admin.Username
	this.successData("", admin)
}

func (this *AdminController) Create() {
	_, err := models.AdminByUsername(this.GetString("username"))
	if err == nil {
		this.errors("用户名已存在", 1)
	}
	var pathUrl string
	var name string
	f, h, err := this.GetFile("image")
	if err == nil {
		defer f.Close()
		name = libs.Md5(strconv.FormatInt(time.Now().Unix(), 10)) + path.Ext(h.Filename)
		pathUrl = "static/upload/" + name
		this.SaveToFile("image", pathUrl)
	}
	Admin := new(models.Admin)
	Admin.Username = this.GetString("username")
	Admin.Password = libs.PasswordMake(this.GetString("password"))
	if this.GetString("name") != "" {
		Admin.Name = this.GetString("name")
	}
	if name != "" {
		Admin.Image = name
	}
	orm.NewOrm().Insert(Admin)
	this.success("")
}

func (this *AdminController) List() {
	page, err := this.GetInt("page")
	if err != nil {
		page = 1
	}
	limit, err := this.GetInt("limit")
	if err != nil {
		limit = 20
	}
	result, total := models.AdminList(page, limit)
	list := make([]map[string]interface{}, len(result))
	for k, v := range result {
		row := make(map[string]interface{})
		row["admin_id"] = v.Id
		row["username"] = v.Username
		row["name"] = v.Name
		row["image"] = v.Image
		if v.Image != "" {
			row["image"] = "/upload/" + v.Image
		}
		row["created_at"] = v.Created_at.Format("2006-01-01 15:04:05")
		row["updated_at"] = v.Updated_at.Format("2006-01-01 15:04:05")
		list[k] = row
	}
	listData := make(map[string]interface{})
	listData["total"] = total
	listData["data"] = list
	this.successData("", listData)
}

func (this *AdminController) Delete() {
	id, _ := this.GetInt("admin_id")
	_, err := orm.NewOrm().Delete(&models.Admin{Id: id})
	if err == nil {
		this.success("")
	} else {
		this.errors("", 1)
	}
}

func (this *AdminController) Update() {
	id, _ := this.GetInt("admin_id")

	admin := models.Admin{Id: id}
	if orm.NewOrm().Read(&admin) != nil {
		this.errors("未找到,请刷新重试", 1)
	}

	admin.Name = this.GetString("name")
	if _, err := orm.NewOrm().Update(&admin); err != nil {
		this.errors("更新失败,请刷新重试", 1)
	}
	this.success("")
}
